<template>
  <div class="monitorCdrpeer report">
    <el-form label-position="left" :inline="true">
      <div>
          <el-form-item class="display-in margin-r" :label="$t('public.agent')">
            <!-- 通话座席日志，使用AgentSearch组件时，需要多传一个参数，用来在组件中判断 -->
            <AgentSearch :module="'call'" :isMonitorCallLog="true" power="call" ref="agentSearch" class="display-in" :disableShow="true"></AgentSearch>
          </el-form-item>
      </div>
      <div>
        <el-form-item class="display-in" :label="''">
          <el-checkbox v-model="form.status">{{$t('monitor.statusChangeSearch')}}</el-checkbox>
        </el-form-item>
      </div>
      <div>
        <el-form-item class="display-in margin-r" v-show="form.status">
          <el-select v-model="form.callStatus" collapse-tags
                     :multiple="true"
                     style="width: 220px;"
                     :placeholder="$t('public.pleasePick')">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="display-in" style="line-height: 40px" :label="form.status ? '' : $t('monitor.bAndETime')">
          <el-date-picker size="mini"
                          style="height: 30px;margin-top: 5px"
                          class="date-choose"
                          v-model="form.date"
                          :id="['monitorDate1','monitorDate2']"
                          type="datetimerange"
                          :editable="false"
                          :picker-options="pickerOptions2"
                          :placeholder="$t('sms.choTimeScope')"
                          align="right">
          </el-date-picker>
        </el-form-item>
      </div>
    </el-form>
    <div class="btn-wrap">
      <el-button class="primary_btn report_excel_btn" @click.stop="resetForm">{{$t('public.reset')}}</el-button>
      <el-button type="primary" class="primary_btn" @click.stop="searchCdrpeer">{{$t('public.search2')}}</el-button>
    </div>
    <div style="height: 20px; width: 100%">
      <affix v-show="!isCallDeatil" :label="$t('monitor.seatStateLogSearchResult')"></affix>
      <BreadCrumbConfig v-show="isCallDeatil" :titleArr="titleArr" @back="cancle"></BreadCrumbConfig>
    </div>
    <div class="btn-wrap" v-show="!isCallDeatil">
      <el-button class="primary_btn" @click.stop="exportCdrPeer">{{$t('report.exportXls')}}</el-button>
      <el-popover
        v-show="!form.status"
        placement="bottom"
        width="540"
        trigger="hover"
      >
        <div v-html="$t('monitor.excelTip')" style="font-size: 12px; padding: 5px;line-height:20px"></div>
        <span slot="reference" class="tooltip"><el-button class="primary_btn export-detail" @click.sotp="exportDetailCdrPeer">{{$t('monitor.expoltDetailEXCEL')}}</el-button></span>
      </el-popover>
      <el-button class="primary_btn" v-on:click.stop="config" style="margin-left: 20px" v-if="configHeaderShow && (!form.status)">{{$t('report.setHeaderConfig')}}</el-button>
    </div>
    <div class="deploy" v-show="!isCallDeatil">
      <el-collapse accordion>
        <el-collapse-item>
          <template slot="title">
            <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
          </template>
          <div>
            {{$t('monitor.agentStateLogTip1')}}<br>
            {{$t('monitor.agentStateLogTip2')}}<br>
            {{$t('monitor.agentStateLogTip3')}}<br>
            {{$t('monitor.agentStateLogTip4')}}<br>
            {{$t('monitor.agentStateLogTip5')}}<br>
            {{$t('monitor.agentStateLogTip6')}}<br>
            {{$t('monitor.agentStateLogTip7')}}<br>
            {{$t('monitor.agentStateLogTip8')}}<br>
            {{$t('monitor.agentStateLogTip9')}}<br>
            {{$t('monitor.agentStateLogTip10')}}<br>
            {{$t('monitor.agentStateLogTip11')}}<br>
            {{$t('monitor.agentStateLogTip12')}}<br>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <!--下边表格展示============================================-->
    <div class="tables" v-show="!isCallDeatil">
      <div class="caption">
        <Pagination
          class="fr"
          :small="true"
          :currentPage="curPage"
          :count="count"
          @turnPage="handleCurrentChange"
          :totalPage="Math.ceil(count/pageSize)"
        >
        </Pagination>
      </div>
      <!--表格===============================================-->
      <div>
        <el-table :data="tableData"
                  ref="elTable"
                  style="width: 100%"
                  class="monitor-cdr-table"
                  v-loading="tableLoading"
                  size="mini">
          <el-table-column
            v-for="(item, index) in headOptions.Config"
            v-if="item.show === true"
            :key="index"
            :prop="item.name"
            :label="item.displayname">
          </el-table-column>
          <el-table-column
            v-if="!isShowImDetail"
            width="160"
            fixed="right"
            key="option"
            prop="option"
            :label="$t('monitor.operate')">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click.stop="exportDetail(scope.row)">{{$t('public.exportDetil')}}</el-button>
              <el-button type="text" size="small" @click.stop="showConent(scope.row)">{{$t('call.queryDetail')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--表格==============================================================================-->
      <!--点击查看  dialog 短信详情    start  ===============================================-->
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('monitor.agentStateDetailInfo')" :visible.sync="dialogCdrpeerDetailVisible" width="50%">
        <div class="shuomin">
          <strong>{{$t('monitor.tip')}}</strong>{{$t('monitor.tipContent')}}
        </div>
        <div class="caption">
          <Pagination
            class="fr"
            :small="true"
            :currentPage="pageForDetail"
            :count="countForDetail"
            @turnPage="handleCurrentDetail"
            :totalPage="Math.ceil(countForDetail/pageSize)"
          >
          </Pagination>
        </div>
        <!--表格===============================================-->
        <el-table :data="tableDataForDetail" stripe style="width: 100%" v-loading="tableLoading" size="mini">
          <el-table-column prop="agentName" :label="$t('public.agent')"></el-table-column>
          <el-table-column prop="EXTEN_TYPE_NAME" :label="$t('monitor.loginType')"></el-table-column>
          <el-table-column prop="BEGIN_TIME" :label="$t('monitor.beginTime')"></el-table-column>
          <el-table-column prop="END_TIME" :label="$t('monitor.endTime')"></el-table-column>
          <el-table-column prop="busyTimeLen" :label="$t('monitor.stateTime')"></el-table-column>
          <el-table-column prop="BUSY_TYPE_NAME" :label="$t('monitor.state')"></el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button class="primary_btn" @click.stop="dialogCdrpeerDetailVisible = false">{{$t('sms.close')}}</el-button>
        </div>
      </el-dialog>
      <!--点击查看  dialog 短信详情    end   ===============================================-->
    </div>
    <header-option v-show="isShowConfig" :show="isShowConfig" :option="headOptionsShow" :type="type" @close="close"></header-option>
    <div :class="dialogShow ? 'layout-qua-bus' : 'layin-qua-bus'" class="business-qua-dialog">
      <h2 class="title">{{$t('monitor.agentDetail')}}
        <div v-show="dialogShow" class="close fr" @click="closeWindow"><i class="el-icon-close"></i></div>
      </h2>
      <div class="scroll">
        <Pagination
          class="fr"
          :small="true"
          :currentPage="curPageDD"
          :count="countDD"
          @turnPage="handleCurrentChangeDD"
          :totalPage="Math.ceil(countDD/pageSize)">
        </Pagination>
        <el-table :data="tableDataDD" style="width: 100%" v-loading="tableLoadingDD">
          <el-table-column
            v-for="(item) in detailTableHeaderD"
            v-if="item.show === true"
            :key="item.name"
            :prop="item.name"
            :label="item.displayname">
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div v-if="isCallDeatil" style="margin-top: 20px">
      <div class="caption">
        <Pagination
          class="fr"
          :small="true"
          :currentPage="curPageD"
          :count="countD"
          @turnPage="handleCurrentChangeD"
          :totalPage="Math.ceil(countD/pageSize)">
        </Pagination>
      </div>
      <el-table :data="tableDataD" style="width: 100%" size="mini">
        <el-table-column
          :width="item.name === 'BEGIN_TIME' || item.name === 'END_TIME' || item.name === 'loginTime' || item.name === 'logoutTime' || item.name === 'IP_MESSAGE' || item.name === 'loginIp' ? '160' : ''"
          v-if="item.name"
          v-for="(item) in detailTableHeader"
          :key="item.name"
          :prop="item.name"
          :label="item.displayname">
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('monitor.operate')">
          <template slot-scope="scope">
            <el-button
              v-if="tableDataD[scope.$index].busyTimeLength !== 0 || tableData[scope.$index].END_TIME === null"
              type="text"
              @click.stop="showDetail(scope.row)"
              size="small">{{$t('sms.searchToLook')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
  import affix from './../../ui-modules/affix/Affix.vue'
  import {getFormatDateTime, deepClone, getCallTimeLength} from '@/utils/m7Utils.js'
  import Pagination from '@/components/public-modules/card/Pagination'
  import headerOption from '../report/base/headerOption'
  import AgentSearch from './base/AgentSearch.vue'
  import BreadCrumbConfig from '@/components/ui-modules/breadCrumb/monitorBreadCrumb'
  export default {
    name: 'MonitorCdrpeer',
    data () {
      return {
        usersArr: [], // 后端返回
        isHidden: false,
        isZero: false,
        isCallDeatil: false,
        titleArr: [this.$t('monitor.callLog'), this.$t('monitor.agentStatusLog')],
        optionsCurrent: {
          start: '00:00',
          step: '00:30',
          end: '23:30'
        },
        rowsObj: {},
        isShowImTime: false,
        curPageDD: 1,
        tableLoadingDD: false,
        dialogShow: false,
        type: 'call_monitor_agent_status_log',
        isShowConfig: false,
        headOptionsShow: {},
        agents: [],
        phoneBars: [],
        tableDataDD: [],
        detailTableHeaderD: [
          {
            show: true,
            name: 'AGENT_NAME',
            displayname: this.$t('public.agent')
          },
          {
            show: true,
            name: 'EXTEN',
            displayname: this.$t('public.jobNumber')
          },
          {
            show: true,
            name: 'BUSY_TYPE_NAME',
            displayname: this.$t('monitor.state')
          },
          {
            show: true,
            name: 'EXTEN_TYPE_NAME',
            displayname: this.$t('monitor.loginTypeNew')
          },
          {
            show: true,
            name: 'BEGIN_TIME',
            displayname: this.$t('monitor.beginTime')
          },
          {
            show: true,
            name: 'END_TIME',
            displayname: this.$t('monitor.endTime')
          },
          {
            show: true,
            name: 'TIME_LENGTH',
            displayname: this.$t('monitor.stateTime')
          },
          {
            show: true,
            name: 'OPERATOR_NAME',
            displayname: this.$t('monitor.adminOpeate')
          }
        ],
        detailTableHeaderCenter: [
          {
            name: 'agentName',
            displayname: this.$t('public.agent')
          },
          {
            name: 'agentNo',
            displayname: this.$t('public.jobNumber')
          },
          {
            name: 'BEGIN_TIME',
            displayname: this.$t('monitor.loginTime')
          },
          {
            name: 'EXTEN_TYPE_NAME',
            displayname: this.$t('monitor.loginTypeNew')
          },
          {
            name: 'IP_MESSAGE',
            displayname: this.$t('monitor.loginIp')
          },
          {
            name: 'END_TIME',
            displayname: this.$t('public.leaveTime')
          },
          {
            name: 'TIME_LENGTH',
            displayname: this.$t('monitor.onlineTime')
          },
          {
            name: 'busyTimeLength',
            displayname: this.$t('monitor.busyTime')
          },
          {
            name: 'vacaTimeLength',
            displayname: this.$t('monitor.waitTimeLength')
          },
          {
            name: 'idleTimeLength',
            displayname: this.$t('monitor.freeTimeLength')
          },
          {
            name: 'customStatusTimeLength',
            displayname: this.$t('monitor.selfTimeLength')
          },
          {
            name: 'autoBusyTimeLength',
            displayname: this.$t('monitor.autoBusyTimeLength')
          },
          {
            name: 'BUSYTYPE',
            displayname: this.$t('monitor.busyType')
          },
          {
            name: 'vacaNum',
            displayname: this.$t('monitor.vacaNum')
          },
          {
            name: 'busyNum',
            displayname: this.$t('monitor.busyNum')
          },
          {
            name: 'idleNum',
            displayname: this.$t('monitor.idleNum')
          },
          {
            name: 'customStatusNum',
            displayname: this.$t('monitor.customStatusNum')
          }
        ],
        detailTableHeader: [],
        pickerOptions2: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        isShowImDetail: false,
        headOptions: {
          Config: []
        },
        options: [
          {
            value: 'busy',
            label: this.$t('login.busy')
          },
          {
            value: 'idle',
            label: this.$t('login.idle')
          },
          {
            value: 'vaca',
            label: this.$t('monitor.rest')
          },
          {
            value: 'custom',
            label: this.$t('monitor.custom')
          },
          {
            value: 'postProcessing',
            label: this.$t('monitor.postProcessing')
          },
          {
            value: 'autoBusy',
            label: this.$t('monitor.autoBusy')
          },
          {
            value: 'dialing',
            label: this.$t('cti.dialing')
          }
        ],
        form: {
          type: 'call',
          selectedAgent: '',
          includeSubordinate: false,
          date: [],
          callStatus: [],
          status: false
        },
        y: '',
        m: '',
        d: '',
        queryArry: '',
        tableLoading: false,
        tableLoadingD: false,
        tableDataD: [],
        tableData: [],
        tableDataForDetail: [],
        countD: 0,
        countDD: 0,
        curPageD: 1,
        count: 0,
        pageSize: 10,
        curPage: 1,
        pageForDetail: 1,
        countForDetail: 0,
        dialogCdrpeerDetailVisible: false,
        BEGIN_TIME_DETAIL: '',
        END_TIME_DETAIL: '',
        AGENT_DETAIL: '',
        expandId: '',
        expandObj: {}
      }
    },
    inject: ['configHeaderShow'],
    methods: {
      // 点击查询按钮
      searchCdrpeer () {
        this.usersArr = []
        this.curPage = 1
        this.isCallDeatil = false
        this.search()
      },
      // 重置form表单
      resetForm () {
        this.form.status = false
        this.form.date = [new Date(this.y, this.m, this.d), new Date(this.y, this.m, this.d, 23, 59, 59)]
        this.form.callStatus = []
        this.form.includeSubordinate = false
        this.$refs.agentSearch.radioChange('agent')
      },
      // 点击面包屑导航 返回到查询列表的初始状态
      cancle () {
        this.isCallDeatil = false // isCallDeatil 参数是否展示通话日志详情
      },
      getMoreStatusData (row) {
        let BEGIN, END
        if (this.form.date) {
          if (this.form.date[0]) {
            BEGIN = getFormatDateTime(this.form.date[0])
          }
          if (this.form.date[1]) {
            END = getFormatDateTime(this.form.date[1])
          }
        }
        //        开始时间或者结束时间不能为空
        if (!BEGIN || !END) {
          this.$message.error(this.$t('monitor.timeWrongTip'))
          return
        }
        let data = {
          startTime: BEGIN,
          endTime: END,
          page: this.curPageDD,
          agentId: row._id,
          pageSize: this.pageSize
        }
        this.handleMoreStatusData(data)
      },
      // 查看通话详情
      showConent (row) {
        if (row.loginNum === 0 && row.offlineNum === 0) {
          this.isZero = true
          this.rowsObj = row
          this.dialogShow = true
          this.curPageDD = 1
          this.getMoreStatusData(row)
        } else {
          this.isZero = false
          this.isCallDeatil = true // 展示通话日志详情
          this.curPageD = 1 // 详情列表重置页码
          this.expandId = row._id
          this.expandObj = row // 存储用户当前点击的记录
          this.handleExpandCallDetail(row._id) // 查询当前点击的列表的详情
        }
      },
      handleMoreStatusData (data) {
        for (let i = 0; i < this.detailTableHeaderD.length; i++) {
          if (this.detailTableHeaderD[i].name === 'AGENT_NAME' || this.detailTableHeaderD[i].name === 'EXTEN') {
            this.detailTableHeaderD[i].show = false
          }
        }
        this.tableLoadingDD = true
        this.$store.dispatch('getBusyCdrPeer', data).then(res => {
          this.tableLoadingDD = false
          if (res.success) {
            let tableData = res.data || []
            this.countDD = res.count
            tableData.forEach(item => {
              // 在线时长
              let beginTime = item.BEGIN_TIME
              let endTime = item.END_TIME
              if (beginTime === null || endTime === null || beginTime === undefined || endTime === undefined) {
                item.TIME_LENGTH = '00:00:00'
              } else {
                let begin = new Date(Date.parse(beginTime.replace(/-/g, '/')))
                let end = new Date(Date.parse(endTime.replace(/-/g, '/')))
                let time = end.getTime() - begin.getTime()
                item.TIME_LENGTH = getCallTimeLength(time / 1000)
              }
              // 登录方式
              if (item.EXTEN_TYPE === 'Local') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.phone')
              } else if (item.EXTEN_TYPE === 'gateway') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.wangguan')
              } else if (item.EXTEN_TYPE === 'sip') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.softPhone')
              } else if (item.EXTEN_TYPE === 'none') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.noPhone')
              }
              // 状态
              this.phoneBars.forEach(one => {
                if (item.BUSY_TYPE === '99') {
                  item.BUSY_TYPE_NAME = this.$t('monitor.autoBusy')
                } else if (item.BUSY_TYPE === '98') {
                  item.BUSY_TYPE_NAME = this.$t('monitor.postProcessing')
                } else if (item.BUSY_TYPE === '97') {
                  item.BUSY_TYPE_NAME = this.$t('cti.dialing')
                } else if (item.BUSY_TYPE === one.PhoneBarItemId) {
                  item.BUSY_TYPE_NAME = one.PhoneBarItemName
                }
              })
              let agent = this.$store.getters.agents[item.OPERATOR]
              item.OPERATOR_NAME = agent ? agent.displayName + '(' + agent.exten + ')' : ''
            })
            this.tableDataDD = tableData
          }
        })
      },
      // 点击查看明细
      showDetail (rows) {
        this.rowsObj = rows
        this.dialogShow = true
        this.curPageDD = 1
        // row当前详情对象
        this.handleGetBusyCdrPeer(rows)
      },
      // 导出通话详情明细，row参数为当前选中要导出的对象
      exportDetail (row) {
        let Query = {}
        let data = {}
        // 格式化查询日期
        let BEGIN, END
        if (this.form.date) {
          if (this.form.date[0]) {
            BEGIN = getFormatDateTime(this.form.date[0])
          }
          if (this.form.date[1]) {
            END = getFormatDateTime(this.form.date[1])
          }
        }
        // 开始时间或者结束时间不能为空
        if (!BEGIN || !END) {
          this.$message.error(this.$t('monitor.timeWrongTip'))
          return
        }
        // 为查询条件赋值
        Query.startTime = BEGIN // 开始时间
        Query.endTime = END // 结束时间
        Query.exten = row.agentNo // 座席工号
        // Query.ASTERISK = this.$store.state.session.user.pbx // 当前用户的pbx
        data.Method = 'exportMonitorCdrPeer' // 导出类型
        Query.agentName = row.agentName // 座席名称
        Query.agentId = row._id // 座席id
        data.Query = Query
        // 调用导出明细接口
        this.$store.dispatch('exportCdrPeer', data).then(() => {})
      },
      // 关闭通话详情明细的浮层
      closeWindow () {
        this.dialogShow = false // 是否展示通话详情的明细
      },
      // 配置表头
      config () {
        let _type = 'call_monitor_agent_status_log'
        this.type = _type
        this.$store.dispatch('getReportTableHeader', _type).then((res) => {
          this.headOptionsShow = res
          this.isShowConfig = !this.isShowConfig // 是否展示表头
        })
      },
      // 关闭配置表头弹框
      close (data) {
        this.isShowConfig = false
        // 如果点击了保存，重新查询列表， 如果当前停留在啦在线客服详情 要重置回最初状态
        if (data === 'save') {
          this.isCallDeatil = false
          this.search()
        }
      },
      showExportDetail (index, obj) {
        console.log(index)
        console.log(obj)
      },
      // 通话详情的明细翻页查询
      handleCurrentChangeDD (val) {
        this.curPageDD = val
        if (this.isZero) {
          this.getMoreStatusData(this.rowsObj)
        } else {
          // rowsObj 为当前通话详情对象
          this.handleGetBusyCdrPeer(this.rowsObj)
        }
      },
      // 处理通话详情数据
      handleExpandCallDetail (_id) { // _id为当前选中点击的列表的id
        let data = {}
        // 格式化日期时间
        if (this.form.date) {
          if (this.form.date[0]) {
            data.startTime = getFormatDateTime(this.form.date[0])
          }
          if (this.form.date[1]) {
            data.endTime = getFormatDateTime(this.form.date[1])
          }
        }
        data.page = this.curPageD // 当前查询的页码
        data.pageSize = this.pageSize // 当前展示多少条
        data.agentId = _id // 座席Id
        this.detailTableHeader = []
        this.detailTableHeader = deepClone(this.detailTableHeaderCenter)  //   详情列表展示 以前的表头  和  自定义状态的表头
        this.headOptions.Config.forEach(item => {
          if (item.dynamic && item.show) {
            this.detailTableHeader.push({name: item.name, displayname: item.displayname})
          }
        })
        this.tableLoadingD = true
        this.$store.dispatch('getlogincdrpeer', data).then(res => {
          this.tableLoadingD = false
          if (res.success) {
            // let tableData = res.data || []
            this.countD = res.count
            let tableDataD = res.data || []
            tableDataD.forEach(item => {
              item.agentName = this.expandObj.agentName // 座席名称
              item.agentNo = this.expandObj.agentNo // 座席工号
              // 登录方式
              if (item.EXTEN_TYPE === 'Local') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.phone')
              } else if (item.EXTEN_TYPE === 'gateway') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.wangguan')
              } else if (item.EXTEN_TYPE === 'sip') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.softPhone')
              } else if (item.EXTEN_TYPE === 'none') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.noPhone')
              }
              // 登录状态
              if (item.BUSY_TYPE === '-1') {
                item.BUSYTYPE = this.$t('monitor.offlineLi')
              } else {
                item.BUSYTYPE = this.$t('monitor.online')
              }
              //  在线时长
              if (item.TIME_LENGTH === 0 || !item.TIME_LENGTH) {
                item.TIME_LENGTH = '00:00:00'
              } else {
                item.TIME_LENGTH = getCallTimeLength(item.TIME_LENGTH)
              }
              // 小休时长
              if (item.vacaTimeLength === 0) {
                item.vacaTimeLength = '00:00:00'
              } else {
                item.vacaTimeLength = getCallTimeLength(item.vacaTimeLength)
              }
              // 空闲时长
              if (item.idleTimeLength === 0) {
                item.idleTimeLength = '00:00:00'
              } else {
                item.idleTimeLength = getCallTimeLength(item.idleTimeLength)
              }
              // 忙碌时长
              if (item.busyTimeLength === 0) {
                item.busyTimeLength = '00:00:00'
              } else {
                item.busyTimeLength = getCallTimeLength(item.busyTimeLength)
              }
              // 置忙时长
              if (item.autoBusyTimeLength === 0) {
                item.autoBusyTimeLength = '00:00:00'
              } else {
                item.autoBusyTimeLength = getCallTimeLength(item.autoBusyTimeLength)
              }
              // 自定义状态时长
              if (item.customStatusTimeLength === 0) {
                item.customStatusTimeLength = '00:00:00'
              } else {
                item.customStatusTimeLength = getCallTimeLength(item.customStatusTimeLength)
              }
              this.headOptions.Config.forEach(theOne => {
                if (theOne.dynamic && theOne.timeType && theOne.show) {
                  if (item[theOne.name] === 0 || !item[theOne.name]) {
                    item[theOne.name] = '00:00:00'
                  } else {
                    item[theOne.name] = getCallTimeLength(item[theOne.name])
                  }
                }
              })
            })
            this.tableDataD = tableDataD // 通话详情数据
          }
        })
      },
      // 处理通话详情的明细
      handleGetBusyCdrPeer (rows) {
        let data = {}
        data.startTime = rows.BEGIN_TIME // 该条通话详情的开始时间
        data.endTime = rows.END_TIME // 该条通话详情的结束时间
        data.page = this.curPageDD
        data.pageSize = this.pageSize
        data.agentId = rows.AGENT
        this.handleMoreStatusData(data)
      },
      // 通话详情翻页
      handleCurrentChangeD (val) {
        this.curPageD = val
        this.handleExpandCallDetail(this.expandId)
      },
      // 通话统计列表翻页
      handleCurrentChange (val) {
        this.curPage = val
        this.search('turnPage')
      },
      // 查询通话统计
      search (val) {
        let _form = this.$refs.agentSearch.form // 获取座席组件的form对象2
        let data = {
          page: this.curPage,
          pageSize: this.pageSize,
          includeSubordinate: _form.includeSubordinate,
          agents: _form.leaf
        }
        // 勾选 显示座席下架  座席不能为空
        if (data.includeSubordinate && data.agents.length === 0) {
          this.$message.error(this.$t('monitor.inputAgentNoToSearch'))
          return
        }
        if (this.form.date) {
          if (this.form.date[0]) {
            data.startTime = getFormatDateTime(this.form.date[0])
          }
          if (this.form.date[1]) {
            data.endTime = getFormatDateTime(this.form.date[1])
          }
        }
        //        开始时间或者结束时间不能为空
        if (!data.startTime || !data.endTime) {
          this.$message.error(this.$t('monitor.timeWrongTip'))
          return
        }
        // this.form.status如果状态为true说明查的是状态的明细
        if (this.form.status) {
          data.status = this.form.callStatus
          this.handkeCallStatus(data)
        } else {
          let start = (this.curPage - 1) * this.pageSize
          let end = this.curPage * this.pageSize
          if (val === 'turnPage') {
            delete data.agents
            data.pageUsers = this.usersArr.slice(start, end)
          } else {
            let len = this.$refs.agentSearch.allAgent.length
            if (len === _form.leaf.length) {
              data.agents = []
            }
            // data.agents = this.usersArr.slice(start, end)
          }
          this.handleCall(data, val)
        }
      },
      // 处理查询的状态明细
      handkeCallStatus (data) {
        this.tableLoading = true
        for (let i = 0; i < this.detailTableHeaderD.length; i++) {
          if (this.detailTableHeaderD[i].name === 'AGENT_NAME' || this.detailTableHeaderD[i].name === 'EXTEN') {
            this.detailTableHeaderD[i].show = true
          }
        }
        this.headOptions.Config = deepClone(this.detailTableHeaderD)
        this.$store.dispatch('getCdrPeerStatusDetails', data).then(res => {
          this.tableLoading = false
          if (res.success) {
            this.isHidden = true
            this.isShowImDetail = true
            let tableData = res.data || []
            this.count = res.count
            tableData.forEach(item => {
              // 在线时长
              let beginTime = item.BEGIN_TIME
              let endTime = item.END_TIME
              if (beginTime === null || endTime === null || beginTime === undefined || endTime === undefined) {
                item.TIME_LENGTH = '--'
              } else {
                let begin = new Date(Date.parse(beginTime.replace(/-/g, '/')))
                let end = new Date(Date.parse(endTime.replace(/-/g, '/')))
                let time = end.getTime() - begin.getTime()
                item.TIME_LENGTH = getCallTimeLength(time / 1000)
              }
              // 登录方式
              if (item.EXTEN_TYPE === 'Local') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.phone')
              } else if (item.EXTEN_TYPE === 'gateway') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.wangguan')
              } else if (item.EXTEN_TYPE === 'sip') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.softPhone')
              } else if (item.EXTEN_TYPE === 'none') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.noPhone')
              }
              // 状态
              this.phoneBars.forEach(one => {
                if (item.BUSY_TYPE === '99') {
                  item.BUSY_TYPE_NAME = this.$t('monitor.autoBusy')
                } else if (item.BUSY_TYPE === '98') {
                  item.BUSY_TYPE_NAME = this.$t('monitor.postProcessing')
                } else if (item.BUSY_TYPE === '97') {
                  item.BUSY_TYPE_NAME = this.$t('cti.dialing')
                } else if (item.BUSY_TYPE === one.PhoneBarItemId) {
                  item.BUSY_TYPE_NAME = one.PhoneBarItemName
                }
              })
              let agent = this.$store.getters.agents[item.OPERATOR]
              item.OPERATOR_NAME = agent ? agent.displayName + '(' + agent.exten + ')' : ''
            })
            this.tableData = tableData
          }
        })
      },
      // 导出excel
      exportCdrPeer () {
        let _form = this.$refs.agentSearch.form // 获取座席组件的form对象
        let data = {}
        let Query = {
          includeSubordinate: _form.includeSubordinate,
          agents: _form.leaf
        }
        let BEGIN, END
        if (this.form.date) {
          if (this.form.date[0]) {
            BEGIN = getFormatDateTime(this.form.date[0])
          }
          if (this.form.date[1]) {
            END = getFormatDateTime(this.form.date[1])
          }
        }
        //        开始时间或者结束时间不能为空
        if (!BEGIN || !END) {
          this.$message.error(this.$t('monitor.timeWrongTip'))
          return
        }
        Query.startTime = BEGIN
        Query.endTime = END
        if (this.form.status) {
          Query.status = this.form.callStatus
          data.Method = 'exportMonitorCdrPeerStatusDetails'
        } else {
          data.Method = 'exportMonitorCdrPeerSummary'
        }
        data.Query = Query
        this.$store.dispatch('exportCdrPeer', data).then(() => {})
      },
      // 导出通话详情
      exportDetailCdrPeer () {
        let _form = this.$refs.agentSearch.form // 获取座席组件的form对象
        let Query = {
          includeSubordinate: _form.includeSubordinate,
          agents: _form.leaf
        }
        let data = {}
        let BEGIN, END
        if (this.form.date) {
          if (this.form.date[0]) {
            BEGIN = getFormatDateTime(this.form.date[0])
          }
          if (this.form.date[1]) {
            END = getFormatDateTime(this.form.date[1])
          }
        }
        //        开始时间或者结束时间不能为空
        if (!BEGIN || !END) {
          this.$message.error(this.$t('monitor.timeWrongTip'))
          return
        }
        Query.startTime = BEGIN
        Query.endTime = END
        data.Method = 'exportMonitorCdrPeerDetails'
        data.Query = Query
        this.$store.dispatch('exportCdrPeer', data).then(() => {})
      },
      // 处理通话查询详情
      searchDetail () {
        let data = {}
        data.startTime = this.BEGIN_TIME_DETAIL
        data.endTime = this.END_TIME_DETAIL
        data.AGENT = this.AGENT_DETAIL
        data.ACTION_TYPE = 'busy'
        data.pageSize = this.pageSize
        data.page = this.pageForDetail
        this.$store.dispatch('queryCdrPeer', data).then(res => {
          if (res.success) {
            let tableData = res.list || []
            this.countForDetail = res.count
            tableData.forEach(item => {
//              处理座席名称
              this.agents.forEach(one => {
                if (item.AGENT === one._id) {
                  item.agentName = one.displayName + '[' + one.exten + ']'
                }
              })
//              登录方式
              if (item.EXTEN_TYPE === 'Local') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.phone')
              } else if (item.EXTEN_TYPE === 'gateway') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.wangguan')
              } else if (item.EXTEN_TYPE === 'sip') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.softPhone')
              } else if (item.EXTEN_TYPE === 'none') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.noPhone')
              }
//              忙碌时长
              if (item.END_TIME && item.BEGIN_TIME) {
                item.busyTimeLen = getCallTimeLength(item.TIME_LENGTH)
              } else {
                item.busyTimeLen = ''
              }
//              状态
              this.phoneBars.forEach(one => {
                if (item.BUSY_TYPE === one.PhoneBarItemId) {
                  item.BUSY_TYPE_NAME = one.PhoneBarItemName
                }
              })
            })
            this.tableDataForDetail = tableData
          }
        })
      },
      handleCurrentDetail (val) {
        this.pageForDetail = val
        this.searchDetail()
      },
      // 处理通话统计的数据
      handleCall (data, val) {
        this.tableLoading = true
        this.$store.dispatch('getCdrPeerSummary', data).then(res => {
          this.tableLoading = false
          if (res.success) {
            if (val !== 'turnPage') {
              this.usersArr = res.users
              this.count = res.count
            }
            this.isHidden = false
            this.isShowImDetail = false
            let tableData = res.data || []
            let headConfig = res.tableHeader.Config
            tableData.forEach(item => {
              headConfig.forEach(theOne => {
                  if (theOne.dynamic && theOne.timeType) {
                    if (item[theOne.name] === 0) {
                      item[theOne.name] = '00:00:00'
                    } else {
                      item[theOne.name] = getCallTimeLength(item[theOne.name])
                    }
                  }
              })
//              忙碌总时长
              if (item.allBusyTime === 0) {
                item.allBusyTime = '00:00:00'
              } else {
                item.allBusyTime = getCallTimeLength(item.allBusyTime)
              }
              //              自定义状态总时长
              if (item.allCustomStatusTime === 0) {
                item.allCustomStatusTime = '00:00:00'
              } else {
                item.allCustomStatusTime = getCallTimeLength(item.allCustomStatusTime)
              }
              //              小休总时长
              if (item.allVacaTime === 0) {
                item.allVacaTime = '00:00:00'
              } else {
                item.allVacaTime = getCallTimeLength(item.allVacaTime)
              }
              //              空闲总时长
              if (item.allIdleTime === 0) {
                item.allIdleTime = '00:00:00'
              } else {
                item.allIdleTime = getCallTimeLength(item.allIdleTime)
              }
              //              总在线时长
              if (item.allOnlineTime === 0) {
                item.allOnlineTime = '00:00:00'
              } else {
                item.allOnlineTime = getCallTimeLength(item.allOnlineTime)
              }
              //              置忙总时长
              if (item.allAutoBusyTime === 0) {
                item.allAutoBusyTime = '00:00:00'
              } else {
                item.allAutoBusyTime = getCallTimeLength(item.allAutoBusyTime)
              }
            })
            this.headOptions = res.tableHeader // 通话的表头
            this.tableData = tableData
          }
        })
      }
    },
    components: {
      BreadCrumbConfig,
      affix,
      Pagination,
      headerOption,
      AgentSearch
    },
    mounted () {
      // 初始化时间段
      this.y = new Date().getFullYear()
      this.m = new Date().getMonth()
      this.d = new Date().getDate()
      this.form.date = [new Date(this.y, this.m, this.d), new Date(this.y, this.m, this.d, 23, 59, 59)]
      let p1 = this.$store.dispatch('getCache', {type: 'agents'})
      let p2 = this.$store.dispatch('getCache', {type: 'phoneBars'})
      Promise.all([p1, p2]).then(([res1, res2]) => {
        this.agents = res1
        this.phoneBars = res2
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl';
  .monitorCdrpeer
    padding 20px
    .tip
      color $c-pink
    .im-time
      width 150px
      margin-right 10px
    .display-in
      display inline-block
    .margin-r
      margin-right 30px
    .ui-affix
      padding-bottom 0
    .btn-wrap
      padding 20px
      padding-right 0px
      text-align right
      .export-detail
        margin-left 20px
    .caption
      color $c-prompt
      height 48px
      line-height 48px
      padding-left 14px
      border 1px solid #ddd
      border-bottom none
      .fr
        padding-top 10px
        height 38px
  .shuomin
    color: $c-prompt;
    margin-bottom: 20px;
  .layout-qua-bus
    width 1000px
    background-color #fff
    transition transform 0.35s
    box-shadow 0 3px 6px rgba(0, 0, 0, .3)
    animation movelayout-bus .4s
    @keyframes movelayout-bus
      0%
        width 0px
      100%
        width 1000px
  .layin-qua-bus
    width:0px
    display none
    transition transform 0.35s
  .business-qua-dialog
    height calc(100vh - 54px)
    overflow-y auto
    position fixed
    right 0
    top 54px
    z-index 30
    box-sizing border-box
    padding 15px 20px
    .title
      line-height 20px
      padding-bottom 10px
      margin-bottom 20px
      border-bottom 1px solid $c-border2
    .close
      font-size 16px
      /*background-color #f2f2f2*/
      cursor pointer
</style>
